package com.cyandpos.pad.login;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import androidx.core.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.cyandpos.pad.R;
import com.cyandpos.pad.common.commondata.BaseResponse;
import com.cyandpos.pad.common.commondata.Urls;
import com.cyandpos.pad.common.netmanager.PosHttpManager;
import com.cyandpos.pad.http.OkHttpUtils;
import com.cyandpos.pad.offline.offlinedb.CursorUtil;
import com.cyandpos.pad.offline.offlinedb.OfflineManager;
import com.cyandpos.pad.posdata.UpdateAppData;
import com.cyandpos.pad.utils.ComSharedPreferences;
import com.cyandpos.pad.utils.log.LogUtils;
import com.google.gson.JsonObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2017/05/09.
 */

public class UpdateApp {

    private Context mContext;// 上下文

    /**
     * 更新对话框的弹出控制,其实是控制不让进行网络访问
     */
    boolean isShowing = false;
    private String mVersion_code;// 版本号
    private String mApp_name = "app-debug";// 版本名字
    private String mVersion_desc;// 版本信息
    private String mVersion_name;// 版本名称
    private String mVersion_path;// 版本下载连接地址
    private String url;

    private ProgressBar mProgressBar;// 进度控件
    private TextView mTextView;

    private boolean mIsCancel = false;// 是否暂停更新下载

    private Dialog mDownloadDialog;// 进度弹框

    private String mSavePath; // 在手机内存储的地址
    private int mProgress;// 下载进度框的更新进度

    private static final int DOWNLOADING = 1;// 正在下载中
    private static final int DOWNLOAD_FINISH = 2;// 下载完成

    String version_old;
    int versionCode_old;


    private ProgressDialog dialog;

    public UpdateApp(Context context) {
        mContext = context;
        getVersion();
        Log.i("9527", "UpdateApp");

        dialog = new ProgressDialog(context);
        dialog.setCancelable(false);
        dialog.setMessage("正在查询更新，请稍等");
    }


    /**
     * 更新下载进度条的方法
     */
    private Handler mUpdateProgressHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOADING:
                    // 更新进度框
                    mProgressBar.setProgress(mProgress);
                    mTextView.setText(mProgress + "%");
                    break;
                case DOWNLOAD_FINISH:
                    // 取消进度框
                    mDownloadDialog.dismiss();
                    installAPK();
            }
        }
    };


    /**
     * 发起更新请求
     */
    public void doHttp() {
        dialog.show();
        if (!isShowing) {
            isShowing = true;
            PosHttpManager.Updata(version_old, new OkHttpUtils.ResultCallback() {
                @Override
                public void onSuccess(JsonObject response) {
                    dialog.dismiss();
                    BaseResponse<UpdateAppData> updateRes = BaseResponse.fromJson(response.toString(),UpdateAppData.class);
                    if(updateRes.getCode().equals("0")){
                        UpdateAppData updateAppData = updateRes.getData();
                        for (int i=0;i<updateAppData.getFiles().size();i++){
                            if (updateAppData.getFiles().get(i).getInx()==0){
                                mVersion_code =updateAppData.getFiles().get(i).getVersion();
                                String App_name =updateAppData.getFiles().get(i).getFilename();
                                url = updateAppData.getFiles().get(i).getUrl();
                                if (App_name != null) {
                                    mApp_name = App_name;
                                }
                                if (url == null || url.equals("")) {
                                    mVersion_path = "http://" + Urls.posAddress + "/" + mApp_name + ".apk";
                                } else {
//                                    mVersion_path = "http://" + url + "/" + mApp_name + ".apk";
                                    mVersion_path = url + "/" + mApp_name ;
                                }
                                LogUtils.e("UPDATEURL", "mVersion_path ="+mVersion_path);
                                showNoticeDialog();
                                break;
                            }
                            //脱机db更新
                            else if(updateAppData.getFiles().get(i).getInx()==1&&updateAppData.getFiles().get(i).getFilename().startsWith("OFFLINE")){
                                String version= ComSharedPreferences.getValueByName("DBVERSION","version",0,"197001010000")+"";
                                String fileVersion =updateAppData.getFiles().get(i).getVersion();
                                String fileName =updateAppData.getFiles().get(i).getFilename();
                                String fileUrl = updateAppData.getFiles().get(i).getUrl();
                                DateFormat fmt =new SimpleDateFormat("yyyyMMddHHmm");
                                try {
                                    Date date = fmt.parse(fileVersion);
                                    Date date1 = fmt.parse(version);
                                    if(OfflineManager.isExists()) {
                                        if (date1.getTime() <date.getTime()) {
                                            showDownloadOfflineDialog(fileUrl + fileName, fileName);
                                            ComSharedPreferences.WriteSharedPreferences("DBVERSION", "version", fileVersion);
                                        }
                                    }else{
                                        showDownloadOfflineDialog(fileUrl + fileName, fileName);
                                        ComSharedPreferences.WriteSharedPreferences("DBVERSION", "version", fileVersion);
                                    }
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }

                            }
                        }
                    }else{
                        Toast.makeText(mContext, "没有新版本程序", Toast.LENGTH_SHORT).show();
                    }
                }
                @Override
                public void onFailure(String msg) {
                    dialog.dismiss();
                    Toast.makeText(mContext, "获取更新异常：" + msg, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }


    /**
     * 弹出提醒更新的弹框
     */
    private void showNoticeDialog() {
        Log.i("9627", isShowing + "    aaaaaaa");
        // 创建弹框
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("提示");
        builder.setCancelable(false);
       /* String[] strings = mVersion_desc.split("；");
        String message = "新版本：" + mVersion_name + "\n";
        for (int i = 0; i < strings.length; i++) {
            Log.e("9527", "拆字符串" + strings[i]);
            message = message + strings[i] + "\n";
        }
        builder.setMessage(message);*/
        builder.setMessage("新程序更新");
        // 设置确定按钮点击事件
        builder.setPositiveButton("确认", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 取消对话框
                dialog.dismiss();
                isShowing = false;
                // 弹出下载进度框
                showDownloadDialog();
            }
        });
        // 设置取消按钮点击事件
        builder.setNegativeButton("暂不更新", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 取消对话框
                isShowing = false;
                dialog.dismiss();
            }
        });
        builder.create().show();
    }


    /**
     * 获取该版本版本信息
     */
    public void getVersion() {
        Log.i("9527", "banbenxinxi");
        try {
            PackageManager manager = mContext.getPackageManager();
            PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), 0);
            version_old = info.versionName;
            versionCode_old = info.versionCode;
            Log.i("9527", "version_now" + version_old + "    versionCode_now" + versionCode_old);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 弹出更新进度框
     */
    private void showDownloadDialog() {
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("正在下载新程序，请稍等");
        // 自定义进度框
        View view = LayoutInflater.from(mContext).inflate(
                R.layout.dialog_update_progress, null);
        mProgressBar = (ProgressBar) view.findViewById(R.id.id_update_progress);
        mTextView = (TextView) view.findViewById(R.id.id_update_textview);
        builder.setView(view);
        // 设置取消按钮
        builder.setNegativeButton("取消", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // 取消对话框
                dialog.dismiss();
                // 取消更新
                mIsCancel = true;
            }
        });

        mDownloadDialog = builder.create();
        mDownloadDialog.show();
        // 下载应用
        downloadAPK();
    }


    /**
     * DB弹出更新进度框
     */
    private void showDownloadOfflineDialog(String dbUrl,  String fileName) {
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle("正在下载数据库文件，请稍等");
        // 自定义进度框
        View view = LayoutInflater.from(mContext).inflate(
                R.layout.dialog_update_progress, null);
        mProgressBar = (ProgressBar) view.findViewById(R.id.id_update_progress);
        mTextView = (TextView) view.findViewById(R.id.id_update_textview);
        builder.setView(view);
        mDownloadDialog = builder.create();
        mDownloadDialog.setCancelable(false);
        mDownloadDialog.show();
        downloadOfflineDb(dbUrl,fileName);
    }

    /**
     * 下载OfflineDb
     */
    private void downloadOfflineDb(final String dbUrl, final String fileName) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    // 判断内存卡是否挂载成功
                    if (Environment.getExternalStorageState().equals(
                            Environment.MEDIA_MOUNTED)) {
                        Log.e("9527", "挂载进来了");
                        // 如果挂载成功,设置保存地址
                        String sdPath = Environment
                                .getExternalStorageDirectory() + "/ChangYiAndPos/Pad_ClientNew_2021/DataBase";
                        // 创建保存地址相关文件夹
                        File dir = new File(sdPath);
                        // 判断此文件夹是否存在
                        if (!dir.exists()) {
                            // 不存在的话新建一个
                            dir.mkdir();
                        }
                        HttpURLConnection conn = (HttpURLConnection) new URL(
                                dbUrl).openConnection();
                        conn.connect();
                        // 获取写入流和文档大小
                        InputStream is = conn.getInputStream();
                        int length = conn.getContentLength();
                        // 创建保存文件
                        File apkFile = new File(sdPath, fileName);
                        FileOutputStream fos = new FileOutputStream(apkFile);
                        // 读取文件
                        int count = 0;
                        byte[] buffer = new byte[1024];
                        // 开始读取
                        while (true) {
                            int numread = is.read(buffer);
                            count += numread;
                            // 获取当前下好的文件占总文件的多少比率
                            mProgress = (int) (((float) count / length) * 100);
                            // 给Handler发送信息更新进度条
                            mUpdateProgressHandler
                                    .sendEmptyMessage(DOWNLOADING);

                            if (numread < 0) {
                                // 如果已经下载完毕跳出循环
                                mUpdateProgressHandler
                                        .sendEmptyMessage(DOWNLOAD_FINISH);
                                break;
                            }
                            // 将读取的部分写入文件中
                            fos.write(buffer, 0, numread);
                        }
                        // 关闭流
                        fos.close();
                        is.close();
                        CursorUtil.Unzip(sdPath+"/"+fileName,sdPath);
                        OfflineManager.open(mContext);//脱机数据库开启
                    } else {

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if(mDownloadDialog!=null){
                        mDownloadDialog.dismiss();
                    }
                }
            }
        }).start();
    }


    /**
     * 下载新版应用
     */
    private void downloadAPK() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    // 判断内存卡是否挂载成功
                    if (Environment.getExternalStorageState().equals(
                            Environment.MEDIA_MOUNTED)) {
                        Log.e("9527", "挂载进来了");
                        // 如果挂载成功,设置保存地址
                        String sdPath = Environment
                                .getExternalStorageDirectory() + "/";
                        mSavePath = sdPath + "ChangYiDownload";
                        // 创建保存地址相关文件夹
                        File dir = new File(mSavePath);
                        // 判断此文件夹是否存在
                        if (!dir.exists()) {
                            // 不存在的话新建一个
                            dir.mkdir();
                        }
                        HttpURLConnection conn = (HttpURLConnection) new URL(
                                mVersion_path).openConnection();
                        conn.connect();
                        // 获取写入流和文档大小
                        InputStream is = conn.getInputStream();
                        int length = conn.getContentLength();
                        // 创建保存文件
                        File apkFile = new File(mSavePath, mApp_name
                                + ".apk");
                        FileOutputStream fos = new FileOutputStream(apkFile);
                        // 读取文件
                        int count = 0;
                        byte[] buffer = new byte[1024];
                        // 开始读取
                        while (!mIsCancel) {
                            int numread = is.read(buffer);
                            count += numread;
                            // 获取当前下好的文件占总文件的多少比率
                            mProgress = (int) (((float) count / length) * 100);
                            // 给Handler发送信息更新进度条
                            mUpdateProgressHandler
                                    .sendEmptyMessage(DOWNLOADING);

                            if (numread < 0) {
                                // 如果已经下载完毕跳出循环
                                mUpdateProgressHandler
                                        .sendEmptyMessage(DOWNLOAD_FINISH);
                                break;
                            }
                            // 将读取的部分写入文件中
                            fos.write(buffer, 0, numread);
                        }
                        // 关闭流
                        fos.close();
                        is.close();
                    } else {

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 安装APK
     */
    protected void installAPK() {
        File apkFile = new File(mSavePath, mApp_name + ".apk");
        if (!apkFile.exists())
            return;

        if(Build.VERSION.SDK_INT>=24) {//判读版本是否在7.0以上
            Uri apkUri = FileProvider.getUriForFile(mContext, "com.cyandpos.andpos.fileprovider", apkFile);//在AndroidManifest中的android:authorities值
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            mContext.startActivity(install);
        } else{
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mContext.startActivity(install);
        }

    }
}
